package com.yaoweigroup.community.ui.shop;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.entity.StringEntity;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.DateUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.utils.L;
import com.yaoweigroup.community.CApplication;
import com.yaoweigroup.community.R;
import com.yaoweigroup.community.adapter.BBSTitleAdapter;
import com.yaoweigroup.community.adapter.LeftAdapter;
import com.yaoweigroup.community.adapter.RightAadapter;
import com.yaoweigroup.community.adapter.ShopAdapter;
import com.yaoweigroup.community.adapter.ShopSelectAdapter;
import com.yaoweigroup.community.adapter.SubShopListAdapter;
import com.yaoweigroup.community.config.Common;
import com.yaoweigroup.community.config.Urls;
import com.yaoweigroup.community.enity.ShopDetail;
import com.yaoweigroup.community.enity.ShopType;
import com.yaoweigroup.community.ui.go.GoHomeActivity;
import com.yaoweigroup.community.util.JsonUtil;
import com.yaoweigroup.community.util.LogUtil;
import com.yaoweigroup.community.util.UtilHttp;

public class ShopListActivity extends Activity implements OnClickListener {

	private PullToRefreshListView shopListView;
	private RelativeLayout left_rl;
	private ShopType type;
	private TextView center_tv;
	private ObjectMapper mapper;
	private ProgressBar progress;
	private ImageView error_iv;
	private SubShopListAdapter adapter;
	private List<ShopDetail> list;

	private TextView type_tv;
	private Dialog dialog;
	private TextView right_tv;

	private PopupWindow popWindow;
	private ListView titlesView;
	private ShopSelectAdapter selctAdapter;
	private List<String> selectList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_shop_list);

		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final View vPopWindow = inflater
				.inflate(R.layout.pop_view, null, false);
		selectList = new ArrayList<String>();
		selectList.add("默认");
		selectList.add("上架时间");
		selectList.add("销量");
		selectList.add("价格");
		selctAdapter = new ShopSelectAdapter(this, selectList);
		titlesView = (ListView) vPopWindow.findViewById(R.id.titlesView);
		titlesView.setAdapter(selctAdapter);
		ProgressBar progress_title = (ProgressBar) vPopWindow
				.findViewById(R.id.progress_title);
		progress_title.setVisibility(View.GONE);
		popWindow = new PopupWindow(vPopWindow, 300, 600, true);
		popWindow.setBackgroundDrawable(new BitmapDrawable());
		popWindow.setFocusable(true);
		popWindow.setOutsideTouchable(true);
		// popWindow.setTouchInterceptor(new OnTouchListener() {
		// @Override
		// public boolean onTouch(View v, MotionEvent event) {
		// if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
		// popWindow.dismiss();
		//
		// return true;
		// }
		//
		// return false;
		// }
		// });
		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		mapper = new ObjectMapper();
		list = new ArrayList<ShopDetail>();
		adapter = new SubShopListAdapter(this, list);
		shopListView = (PullToRefreshListView) findViewById(R.id.shopListView);
		shopListView.setAdapter(adapter);
		left_rl = (RelativeLayout) findViewById(R.id.left_rl);
		left_rl.setOnClickListener(this);
		error_iv = (ImageView) findViewById(R.id.error_iv);
		progress = (ProgressBar) findViewById(R.id.progress);
		center_tv = (TextView) findViewById(R.id.center_tv);
		center_tv.setOnClickListener(this);
		type = (ShopType) getIntent().getSerializableExtra("type");
		type_tv = (TextView) findViewById(R.id.type_tv);
		type_tv.setOnClickListener(this);
		right_tv = (TextView) findViewById(R.id.right_tv);
		right_tv.setOnClickListener(this);
		right_tv.setVisibility(View.VISIBLE);
		type_tv.setVisibility(View.GONE);
		if (type == null)
			return;
		center_tv.setText(type.getTypename());
		type_tv.setText(type.getTypename());
		shopListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				int currentPosition = position - 1;
				ShopDetail detail = list.get(currentPosition);
				Intent intent = new Intent(ShopListActivity.this,
						ShopDetailActivity.class);
				intent.putExtra("detail", detail);
				startActivity(intent);

			}
		});

		shopListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				String label = DateUtils.formatDateTime(
						getApplicationContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE
								| DateUtils.FORMAT_ABBREV_ALL);

				// Update the LastUpdatedLabel
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
				error_iv.setVisibility(View.GONE);
				// Do work to refresh the list here.
				pageNo = 1;
				list.clear();
				adapter.setDataChange(list);
				progress.setVisibility(View.VISIBLE);
				obtainData();
			}
		});

		shopListView
				.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

					@Override
					public void onLastItemVisible() {
						if (isLoadEnd) {
							return;
						}
						obtainData();
					}
				});
		obtainData();
		dialog = createDailog();

		titlesView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {

				switch (arg2) {
				case 0:
					sort = null;
					break;
				case 1:
					sort = "time";
					break;
				case 2:
					sort = "sales";
					break;
				case 3:
					sort = "price";
					break;
				}
				popWindow.dismiss();
				pageNo = 1;
				list.clear();
				adapter.setDataChange(list);
				progress.setVisibility(View.VISIBLE);
				obtainData();
			}
		});
	}

	private void showPopWindow(Context context, View parent) {

		popWindow.showAtLocation(parent, Gravity.TOP, 200, 140);

	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if (popWindow != null && popWindow.isShowing()) {
			popWindow.dismiss();
			popWindow = null;

		}
		return super.onTouchEvent(event);
	}

	private boolean isLoadEnd = false;

	private int pageNo = 1;
	private int pageSize = 10;
	private List<ShopDetail> details;
	private String sort = null;

	private void obtainData() {

		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add("typeid", type.getId());
		jsonUtil.add("pageNo", pageNo);
		jsonUtil.add("pageSize", pageSize);
		jsonUtil.add("sort", sort);
		jsonUtil.add("sorttype", "asc");
		LogUtil.d("wxf", jsonUtil.toString());
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString());
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.getProducts, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						String result = responseInfo.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							if (state == 200) {
								String data = obj.getString("data");
								details = mapper.readValue(data,
										new TypeReference<List<ShopDetail>>() {
										});
								handler.sendEmptyMessage(DATA_SUCCESS);
							} else {
								handler.sendEmptyMessage(DATA_FAIL);
							}

						} catch (Exception e) {
							handler.sendEmptyMessage(DATA_FAIL);
							LogUtil.e("wxf", e.toString());
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(DATA_FAIL);

					}

				});

	}

	public final int DATA_SUCCESS = 0x2210;
	public final int DATA_FAIL = DATA_SUCCESS + 1;

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			progress.setVisibility(View.GONE);
			switch (msg.what) {
			case DATA_SUCCESS:
				if (details != null && details.size() > 0) {
					list.addAll(details);
					adapter.setDataChange(list);

					if (details.size() < pageSize) {
						isLoadEnd = true;
					} else {
						pageNo += 1;
						isLoadEnd = false;
					}
				}
				if (list.size() == 0) {
					error_iv.setVisibility(View.VISIBLE);
				} else {
					error_iv.setVisibility(View.GONE);

				}
				shopListView.onRefreshComplete();
				break;
			case DATA_FAIL:
				error_iv.setVisibility(View.VISIBLE);
				break;
			}
		};
	};

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.left_rl:
			finish();
			break;
		case R.id.center_tv:
			if (dialog != null) {
				rightView.setVisibility(View.GONE);
				dialog.show();
			}

			break;
		case R.id.right_tv:
			showPopWindow(this, right_tv);
			break;
		}
	}

	private ListView leftView;
	private ListView centerView;
	private ListView rightView;
	private LeftAdapter typeAdapter;
	private LeftAdapter leftAdapter;
	private LeftAdapter rightAdapter;
	private List<ShopType> typeList;

	private Dialog createDailog() {

		LayoutInflater lif = getLayoutInflater();
		LinearLayout dialog_rl = (LinearLayout) lif.inflate(R.layout.type_view,
				null);

		leftView = (ListView) dialog_rl.findViewById(R.id.leftView);
		rightView = (ListView) dialog_rl.findViewById(R.id.rightView);
		centerView = (ListView) dialog_rl.findViewById(R.id.centerView);
		final Dialog dialog = new Dialog(this, R.style.QuitDialog);
		dialog.setContentView(dialog_rl);
		Window dialogWindow = dialog.getWindow();
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		dialogWindow.setGravity(Gravity.CENTER);
		lp.width = (int) (300 * Common.PROPORTION); // 宽度
		lp.height = (int) (200 * Common.PROPORTION); // 高度
		dialogWindow.setAttributes(lp);

		typeList = new ArrayList<ShopType>();
		typeAdapter = new LeftAdapter(this, typeList);
		leftView.setAdapter(typeAdapter);

		leftAdapter = new LeftAdapter(this, typeList);
		leftAdapter.setSelectPosition(0);
		centerView.setAdapter(leftAdapter);

		rightAdapter = new LeftAdapter(this, typeList);
		rightView.setAdapter(rightAdapter);
		rightView.setVisibility(View.GONE);
		initType();

		leftView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				twoTypes.clear();
				if (oneTypes != null && oneTypes.size() > 0) {
					for (ShopType type : typeList) {
						if (oneTypes.get(position).getId() == type.getSubid()) {
							twoTypes.add(type);
						}
					}
					typeAdapter.setSelectPosition(position);
					if (twoTypes.size() == 0) {
						Toast.makeText(ShopListActivity.this, "暂无类型数据!", 500)
								.show();
					}
					leftAdapter.setDataChange(twoTypes);

					threeTypes.clear();
					leftAdapter.setDataChange(twoTypes);
					if (twoTypes.size() > 0) {
						threeTypes.add(twoTypes.get(0));
						for (ShopType type : typeList) {
							if (twoTypes.get(0).getId() == type.getSubid()) {
								threeTypes.add(type);
							}
						}
						rightAdapter.setDataChange(threeTypes);
					}
					rightView.setVisibility(View.GONE);
				}
			}
		});
		centerView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				threeTypes.clear();
				threeTypes.add(twoTypes.get(position));
				for (ShopType type : typeList) {
					if (twoTypes.get(position).getId() == type.getSubid()) {
						threeTypes.add(type);
					}
				}
				leftAdapter.setSelectPosition(position);
				rightAdapter.setDataChange(threeTypes);
				rightView.setVisibility(View.VISIBLE);
			}
		});
		rightView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				type = threeTypes.get(arg2);
				center_tv.setText(type.getTypename());

				dialog.dismiss();
				error_iv.setVisibility(View.GONE);
				// Do work to refresh the list here.
				pageNo = 1;
				list.clear();
				adapter.setDataChange(list);
				progress.setVisibility(View.VISIBLE);
				obtainData();
			}
		});
		return dialog;
	}

	private List<ShopType> oneTypes;
	private List<ShopType> twoTypes;
	private List<ShopType> threeTypes;

	private void initType() {
		String data = CApplication.cache.get(Urls.getProductType);
		try {
			typeList = mapper.readValue(data,
					new TypeReference<List<ShopType>>() {
					});
			oneTypes = new ArrayList<ShopType>();
			twoTypes = new ArrayList<ShopType>();
			threeTypes = new ArrayList<ShopType>();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if (typeList.size() > 0) {
			for (ShopType oneType : typeList) {
				if (oneType.getSubid() == 0) {
					oneTypes.add(oneType);
				}
			}
			typeAdapter.setSelectPosition(0);
			typeAdapter.setIsVisible(false);
			typeAdapter.setDataChange(oneTypes);
		}

		if (oneTypes.size() > 0) {
			for (ShopType oneType : typeList) {
				if (oneType.getSubid() == oneTypes.get(0).getId()) {
					twoTypes.add(oneType);
				}
			}
			leftAdapter.setDataChange(twoTypes);
		}
	}
}
